from django.contrib import admin
from apps.users.models import UserProfile
from django.utils.translation import ugettext as _
from django.contrib.auth.forms import (UserChangeForm, )
from .forms import UserCreationForm
from django.contrib.auth import get_user_model

import tablib
from import_export.admin import ImportExportActionModelAdmin
from import_export.widgets import ForeignKeyWidget
from import_export import resources, fields

User = get_user_model()


# Register your models here.

class UserResource(resources.ModelResource):

    def __init__(self, input_contract=None):
        super(UserResource, self).__init__()
        field_list = User._meta.fields
        self.verbose_name_dict = {}
        for i in field_list:
            self.verbose_name_dict[i.name] = i.verbose_name

    # 默认导入导出field的column_name为字段的名称，这里修改为字段的verbose_name
    def get_export_fields(self):
        fields = self.get_fields()
        for field in fields:
            field_name = self.get_field_name(field)
            # 如果有设置 verbose_name，则将 column_name 替换为 verbose_name, 否则维持原有的字段名。
            if field_name in self.verbose_name_dict.keys():
                field.column_name = self.verbose_name_dict[field_name]
        return fields

    def export(self, queryset=None, *args, **kwargs):
        """
        Exports a resource.
        """

        self.before_export(queryset, *args, **kwargs)

        if queryset is None:
            queryset = self.get_queryset()
        headers = self.get_export_headers()
        data = tablib.Dataset(headers=headers)

        gender_choice = {
            "0": "女",
            "1": "男",
        }

        for obj in self.iter_queryset(queryset):
            # 个性化显示 choice 的值
            # obj.gender = gender_choice[obj.gender]
            obj.gender = obj.get_gender_display()
            data.append(self.export_resource(obj))

        self.after_export(queryset, data, *args, **kwargs)

        return data

    class Meta:
        skip_unchanged = True  # 是否跳过的记录出现在导入结果对象
        report_skipped = False  # 所有记录将被导入
        # export_order = ('id', )
        model = User


# class UserProfileAdmin(admin.ModelAdmin):
class UserProfileAdmin(ImportExportActionModelAdmin):
    list_display = (
        'username', 'email', 'phone', 'last_name', 'first_name', 'is_active', 'is_staff', 'is_superuser')
    list_display_links = ('username', 'email', 'phone')
    list_editable = ['is_active', 'is_staff', 'is_superuser']
    # readonly_fields = ['password', ]

    # def get_model_form(self, **kwargs):
    #     """
    #     1.把 django UserCreationForm 拷贝出来修改成自己想要的
    #     2.修改 xadmin 继承表格，改成一步骤的表单
    #     :param kwargs:
    #     :return:
    #     """
    #     if self.org_obj is None:
    #         self.form = UserCreationForm
    #     else:
    #         self.form = UserChangeForm
    #     return super(UserProfileAdmin, self).get_model_form(**kwargs)
    resource_class = UserResource


admin.site.register(UserProfile, UserProfileAdmin)
